package com.emmmya.ocs.config.mybatis.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.emmmya.ocs.modules.system.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 处理新增和更新的基础数据填充，配合BaseEntity和MyBatisPlusConfig使用
 */
@Slf4j
@Component
public class MetaHandler implements MetaObjectHandler  {

    /**
     * 新增数据执行
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        Subject subject = SecurityUtils.getSubject();
        if(subject != null && subject.getPrincipal() != null) {
            User userEntity = (User) subject.getPrincipal();
            this.setFieldValByName("createTime", new Date(), metaObject);
            this.setFieldValByName("createBy", userEntity.getUsername(), metaObject);
            this.setFieldValByName("updateTime", new Date(), metaObject);
            this.setFieldValByName("updateBy", userEntity.getUsername(), metaObject);
        }
    }

    /**
     * 更新数据执行
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
         Subject subject = SecurityUtils.getSubject();
         if(subject != null && subject.getPrincipal() != null) {
            User userEntity = (User) subject.getPrincipal();
            this.setFieldValByName("updateTime", new Date(), metaObject);
            this.setFieldValByName("updateBy", userEntity.getUsername(), metaObject);
        }
    }

}